<template>
  <div class="w-100 h-100 p-4 border-box bg-deep color-white flex-item font3">
    <div class="flex-label h-100 py-4 px-5 border-box bg-cover round-md">
      <el-tree :data="camera_data" @node-click="handleNodeClick" node-key="id" :props="defaultProps" accordion />
    </div>
    <div class="flex-content ml-4 h-100 p-4 border-box bg-cover round-md color-white">
      <template v-if="selectedCamera">
        <div class="camera-info">
          <div id="video-container"></div>
          <div class="ptz-controls">
            <div class="ptz-direction">
            <el-button class="ptz-btn" 
              @click="ptzControl('up')"
              @mousedown.native="startPtz('up')"
              @mouseup.native="stopPtz('up')"
              @mouseleave.native="stopPtz('up')">
              <i class="el-icon-top"></i>
            </el-button>
            <div class="ptz-horizontal">
              <el-button class="ptz-btn" 
                @click="ptzControl('left')"
                @mousedown.native="startPtz('left')"
                @mouseup.native="stopPtz('left')"
                @mouseleave.native="stopPtz('left')">
                <i class="el-icon-back"></i>
              </el-button>
              <el-button class="ptz-btn" 
                @click="ptzControl('right')"
                @mousedown.native="startPtz('right')"
                @mouseup.native="stopPtz('right')"
                @mouseleave.native="stopPtz('right')">
                <i class="el-icon-right"></i>
              </el-button>
            </div>
            <el-button class="ptz-btn" 
              @click="ptzControl('down')"
              @mousedown.native="startPtz('down')"
              @mouseup.native="stopPtz('down')"
              @mouseleave.native="stopPtz('down')">
              <i class="el-icon-bottom"></i>
            </el-button>
            </div>
          </div>
        </div>
      </template>
      <div v-else class="empty-tip">
        请从左侧选择摄像头查看详细信息
      </div>
    </div>
  </div>
</template>

<script>
import { getcamera } from '@/request/api';
import EZUIKit from 'ezuikit-js';
import axios from 'axios';
export default {
  name: 'deviceCamera',
  data() {
    return {
      base_id: "",
      cameraList: [],
      loading: false,
      camera_data: [],
      selectedCamera: null,
      jktokens: {
        value: null
      },
      player: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  mounted() {
    this.getCameraData();
    this.jktokens.value = 'your-access-token';
  },
  beforeDestroy() {
    if (this.player) {
      this.player.stop();
      this.player = null;
    }
  },
  methods: {
    async getCameraData() {
      try {
        this.loading = true;
        const base_id = this.$route.query.base_id;
        if (!base_id) {
          console.error('缺少基地ID参数');
          return;
        }

        const res = await getcamera({ base_id });
        if (res && res.item_list) {
          this.cameraList = res.item_list.map(item => ({
            videoAddress: item.video_address,
            serialNumber: item.serial_number,
            state: item.state,
            name: item.camera_name,
            location: item.camera_location
          }));
          
          this.camera_data = this.cameraList.map(camera => ({
            id: camera.serialNumber,
            label: camera.name,
            type: 'CAMERA',
            data: camera
          }));
        }
      } catch (error) {
        console.error('获取摄像头数据失败:', error);
      } finally {
        this.loading = false;
      }
    },

    async handleNodeClick(data) {
      try {
        console.log('Node clicked:', data);
        if (!data || typeof data !== 'object') {
          throw new Error('Invalid node data');
        }
        
        if (data.type === 'CAMERA') {
          this.selectedCamera = data;
          
          if (this.player) {
            this.player.stop();
            this.player = null;
          }

          await this.getToken();

          await this.$nextTick();
          const videoContainer = document.getElementById('video-container');
          if (videoContainer) {
            this.initPlayer(data.data.videoAddress, data.data.serialNumber);
          } else {
            console.error('video-container元素未找到');
          }
        }
      } catch (error) {
        console.error('处理节点点击时出错:', error);
        this.$message.error('无法加载摄像头信息');
      }
    },

    async initPlayer(url, serialNumber) {
      if (!serialNumber || !this.jktokens.value) {
        console.error('设备序列号或访问令牌未设置');
        return;
      }

      if (!window.EZUIKit) {
        console.error('EZUIKit未加载');
        return;
      }

      const videoContainer = document.getElementById('video-container');
      if (!videoContainer) {
        console.error('video-container元素未找到');
        return;
      }

      videoContainer.innerHTML = '';

        try {
          videoContainer.innerHTML = '<div class="loading">加载中...</div>';

          if (!window.EZUIKit || !window.EZUIKit.EZUIKitPlayer) {
            throw new Error('EZUIKit未正确加载');
          }

          if (!this.jktokens.value) {
            throw new Error('访问令牌无效');
          }

          if (!url || typeof url !== 'string') {
            throw new Error('视频地址无效');
          }

          await new Promise(resolve => setTimeout(resolve, 500));

          const playerInstance = new EZUIKit.EZUIKitPlayer({
            id: 'video-container',
            accessToken: this.jktokens.value,
            url: url,
            height: '540',
            width: '960',
            template: 'e33cecdfc3bb4019a06591a15cda2b1f',
            autoplay: true,
            footer: ['fullScreen'],
            handleError: (e) => {
              console.error('播放器错误:', e);
              this.$message.error('视频加载失败: ' + e.message);
              videoContainer.innerHTML = '<div class="error">视频加载失败: ' + e.message + '</div>';
            }
          });

          if (!playerInstance || typeof playerInstance !== 'object') {
            throw new Error('播放器实例创建失败');
          }

          await new Promise(resolve => setTimeout(resolve, 1000));

          if (typeof playerInstance.on === 'function') {
            playerInstance.on('play', () => {
              console.log('播放器开始播放');
            });

            playerInstance.on('error', (e) => {
              console.error('播放器错误:', e);
              this.$message.error('播放器错误: ' + e.message);
              videoContainer.innerHTML = '<div class="error">播放器错误: ' + e.message + '</div>';
            });

            playerInstance.on('dblclick', () => {
              if (typeof playerInstance.fullScreen === 'function') {
                playerInstance.fullScreen();
              }
            });
          } else {
            console.warn('播放器实例不支持事件监听');
          }

          this.player = playerInstance;
      } catch (error) {
        console.error('播放器初始化失败:', error);
        this.$message.error('播放器初始化失败');
      }
    },

    async ptzControl(direction) {
      if (!this.player || !this.selectedCamera) {
        this.$message.warning('请先选择摄像头');
        return;
      }

      try {
        await this.startPtz(direction);
        // 添加停止移动逻辑
        setTimeout(async () => {
          await this.stopPtz(direction);
        }, 500);
      } catch (error) {
        console.error('云台控制失败:', error);
        this.$message.error('云台控制失败');
      }
    },

    async startPtz(direction) {
      if (!this.player || !this.selectedCamera) return;
      
      const commandMap = {
        up: 0,
        down: 1, 
        left: 2,
        right: 3
      };
      
      const serialNumber = this.selectedCamera.data.serialNumber;
      await axios.post('https://open.ys7.com/api/lapp/device/ptz/start',
        `accessToken=${this.jktokens.value}&deviceSerial=${serialNumber}&channelNo=1&direction=${commandMap[direction]}&speed=1`,
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }
      );
    },

    async stopPtz(direction) {
      if (!this.player || !this.selectedCamera) return;
      
      const serialNumber = this.selectedCamera.data.serialNumber;
      await axios.post('https://open.ys7.com/api/lapp/device/ptz/stop',
        `accessToken=${this.jktokens.value}&deviceSerial=${serialNumber}&channelNo=1`,
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }
      );
    },

    async getToken() {
      try {
        const appKey = '3d0be5dc16b846e58ba2e4efb80d6d7f';
        const appSecret = '1d040ec6b1a4d12061fa97ef21987942';

        const response = await axios.post('https://open.ys7.com/api/lapp/token/get',
          `appKey=${appKey}&appSecret=${appSecret}`,
          {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }
        );
        
        this.jktokens.value = response.data.data.accessToken;
        console.log('获取Token成功:', response.data.data.accessToken);
      } catch (error) {
        console.error('获取Token失败:', error);
        this.$message.error('获取访问令牌失败');
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/assets/style/variable.less';

/deep/ .el-tree {
  background: transparent;
  color: @colorWhite;
}

.camera-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.ptz-controls {
  margin-top: 20px;
  display: flex;
  gap: 30px;
}

.ptz-direction {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.ptz-horizontal {
  display: flex;
  gap: 60px;
}

.ptz-btn {
  width: 60px;
  height: 60px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  border-radius: 8px;
  transition: all 0.2s ease;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
  }
}

.stop-btn {
  background: rgba(255, 99, 71, 0.2);
  border-color: rgba(255, 99, 71, 0.3);
  
  &:hover {
    background: rgba(255, 99, 71, 0.3);
    border-color: rgba(255, 99, 71, 0.4);
  }
}

#video-container {
  width: 960px;
  height: 540px;
  background: #000;
}
</style>
